import cloudbase from '../utils/cloudbase';

/**
 * 游戏记录服务
 */
const gameService = {
  /**
   * 添加游戏记录
   * @param {Object} recordData 游戏记录数据
   * @returns {Promise} 添加结果
   */
  async addGameRecord(recordData) {
    try {
      const result = await cloudbase.callFunction({
        name: 'gameRecords',
        data: {
          action: 'add',
          data: recordData
        }
      });
      
      if (result.code !== 0) {
        throw new Error(result.msg || '添加游戏记录失败');
      }
      
      return result.data;
    } catch (error) {
      console.error('添加游戏记录失败:', error);
      throw error;
    }
  },

  /**
   * 获取游戏记录列表
   * @param {Object} params 查询参数
   * @returns {Promise} 游戏记录列表
   */
  async getGameRecords(params = {}) {
    try {
      const result = await cloudbase.callFunction({
        name: 'gameRecords',
        data: {
          action: 'get',
          data: params
        }
      });
      
      if (result.code !== 0) {
        throw new Error(result.msg || '获取游戏记录失败');
      }
      
      return result.data;
    } catch (error) {
      console.error('获取游戏记录失败:', error);
      throw error;
    }
  },

  /**
   * 获取排行榜数据
   * @param {Object} params 查询参数
   * @returns {Promise} 排行榜数据
   */
  async getLeaderboard(params = {}) {
    try {
      const result = await cloudbase.callFunction({
        name: 'gameRecords',
        data: {
          action: 'getLeaderboard',
          data: params
        }
      });
      
      if (result.code !== 0) {
        throw new Error(result.msg || '获取排行榜失败');
      }
      
      return result.data;
    } catch (error) {
      console.error('获取排行榜失败:', error);
      throw error;
    }
  },

  /**
   * 获取游戏记录详情
   * @param {String} id 记录ID
   * @returns {Promise} 游戏记录详情
   */
  async getGameRecordById(id) {
    try {
      const result = await cloudbase.callFunction({
        name: 'gameRecords',
        data: {
          action: 'getById',
          data: { id }
        }
      });
      
      if (result.code !== 0) {
        throw new Error(result.msg || '获取游戏记录详情失败');
      }
      
      return result.data;
    } catch (error) {
      console.error('获取游戏记录详情失败:', error);
      throw error;
    }
  }
};

export default gameService;